package com.sk.bilibili.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.view.View;

import com.sk.bilibili.R;
import com.sk.bilibili.databinding.ActivityRegisterBinding;
import com.sk.bilibili.model.activity.RegisterModel;
import static com.sk.bilibili.utils.StringUtils.str;

public class RegisterActivity extends BaseActivity<ActivityRegisterBinding, RegisterModel> {

    @Override
    protected void afterSetView() {
        initView();
        initEvent();
    }

    private Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            lastTime--;
            if(lastTime>0){
                bind.tvSend.setText(String.format("%ds后重试",lastTime));
                handler.sendEmptyMessageDelayed(COUNT_DOWN,1000);
            }else {
                bind.tvSend.setTextColor(getColor(R.color.pink));
                bind.tvSend.setText("获取验证码");
            }
        }
    };

    private int lastTime=0;
    private static final int COUNT_DOWN=0;

    private void initEvent() {
        bind.tvSend.setOnClickListener(v -> {
            if(lastTime>0)return;
            model.sendMsg(bind.etPhone.getText().toString());
        });
        bind.btnRegister.setOnClickListener(v ->
                model.registerAndLogin(str(bind.etPhone),str(bind.etPassword),str(bind.etCode)));
    }

    private void initView() {
        bind.tvShow.setText(model.getText(getResources().getColor(R.color.pink, getTheme())));
    }

    public void sendSuccess() {
        toast("短信发送成功");
        lastTime=60;
        bind.tvSend.setTextColor(getColor(R.color.gray));
        handler.sendEmptyMessageDelayed(COUNT_DOWN,1000);
    }

    public void sendError(String message) {
        toast(message);
    }

    public void loginSuccess() {
        startActivity(MainActivity.class,true);
    }

    public void loginError(String message) {
        toast(message);
    }

    public void registerError(String message) {
        toast(message);
    }

    public void changePhoneNumType(View view) {
        toast("暂时只支持中国大陆");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(COUNT_DOWN);
    }

}